﻿using System.IO;
using System.Linq;
using System.Net;
using Newtonsoft.Json.Linq;
using Samurai.Infrastructure;

namespace Samurai.MovieIndustry
{
    public class ImdbMovieService : IMovieService
    {
        public Movie GetInfo(string query)
        {
            var req = WebRequest.Create(string.Format("http://www.deanclatworthy.com/imdb/?q={0}", query));

            var response = req.GetResponse();

            var responseStream = response.GetResponseStream();
            var reader = new StreamReader(responseStream);
            var data = reader.ReadToEnd();

            var o = JObject.Parse(data);

            var title = (string)o.SelectToken("title");
            var genres = (string)o.SelectToken("genres");
            var rating = (string)o.SelectToken("rating");
            var year = (string)o.SelectToken("year");

            var error = (string)o.SelectToken("error");

            var url = (string)o.SelectToken("imdburl");

            var info = new Movie
            {
                Title = title,
                Rating = rating,
                Year = year,
                Error = error,
                Genres = BuildGenreTitles(genres),
                Url = url
            };


            return info;

        }

        private static string[] BuildGenreTitles(string genres)
        {
            if (genres == null)
                return new string[] { };

            return genres.Split(',').Select(s => s.Trim(' ')).ToArray();
        }
    }
}
